package com.darren.center.design.patterns.webservice.impl;

import com.darren.center.design.patterns.command.Dispatcher;
import com.darren.center.design.patterns.controller.BaseController;
import com.darren.center.design.patterns.dto.Context;
import com.darren.center.design.patterns.webservice.OpenWebService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

/**
 * <h3>design-patterns</h3>
 * <p></p>
 *
 * @author : Darren
 * @date : 2021年06月14日 18:35:10
 **/

@WebService(name = "OpenWebService", serviceName = "OpenWebService", targetNamespace = "http://api.darren.center.com/services/ws")
@SOAPBinding(use = SOAPBinding.Use.LITERAL, style = SOAPBinding.Style.DOCUMENT)
public class OpenWebServiceImpl implements OpenWebService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private WebServiceContext wsContext;

    @WebMethod
    @WebResult(name = "healthServiceReturn")
    public String healthService(@WebParam(name = "xmlString") String reqXml) {
        Context context = getSjContext();
        context.setClientIP(getClientInfo());
        String respXml = dispatcher.doAction(reqXml, context);
        return respXml;
    }

    private String getClientInfo() {
        String clientIP = null;
        try {
            MessageContext mc = wsContext.getMessageContext();
            HttpServletRequest request = (HttpServletRequest) (mc
                    .get(MessageContext.SERVLET_REQUEST));
            clientIP = BaseController.getIpAddr(request);
        } catch (Exception e) {
            logger.error("getClientInfo异常", e);
        }

        return clientIP;

    }

    private Context getSjContext() {
        return new Context();
    }

    private Dispatcher dispatcher;

    @WebMethod(exclude = true)
    public Dispatcher getDispatcher() {
        return dispatcher;
    }

    @WebMethod(exclude = true)
    public void setDispatcher(Dispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

}


